package com.yunchen.server.service;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunchen.server.mapper.BaseDaoMapper;
import com.yunchen.server.mapper.UserRolesMapper;
import com.yunchen.server.mapper.UsersMapper;
import com.yunchen.server.pojo.*;
import com.yunchen.server.util.MyUtil;
import com.yunchen.server.util.Return;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@Service
public class UsersService {
    @Autowired
    private BaseDaoMapper baseDaoMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private LoginLogsService loginLogsService;
    @Autowired
    private UserRolesMapper userRolesMapper;

    public Return Login(Users users, HttpServletRequest request) {
        Return re = new Return();
        List<Users> user = getUsername(users.getUsername());
        if (user.size()>0){
            Users us = user.get(0);
            if (users.getPassword().equals(us.getPassword())){
                if (us.getStatus()==1){
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("users",us);
                    StpUtil.login(us.getUserId());
                    jsonObject.put("token",StpUtil.getTokenValue());
                    re.setData(jsonObject);
                    re.setCode(200);
                    re.setMsg("成功");
                    loginLogsService.Add(us.getUserId(),1,"登录成功",request);
                    deng(us.getUserId(),request);
                }else {
                    loginLogsService.Add(us.getUserId(),0,"此账号禁止登录",request);
                    re.setCode(203);
                    re.setMsg("此账号禁止登录，有问题请联系管理员！");
                }

            }else {
                loginLogsService.Add(us.getUserId(),0,"密码不对",request);
                re.setCode(202);
                re.setMsg("密码不对");
            }
        }else {
            re.setCode(201);
            re.setMsg("账号密码不对");
        }
        return re;
    }


    public List<Users> getUsername(String username) {
        UsersExample usersExample=new UsersExample();
        usersExample.createCriteria().andUsernameEqualTo(username);
        List<Users> users = usersMapper.selectByExample(usersExample);
        return users;
    }
    public void deng(Long user_id, HttpServletRequest request) {
        Users users=new Users();
        users.setUserId(user_id);
        users.setLastLoginTime(new Date());
        String ipAddr = MyUtil.getIpAddrReal(request);
        users.setLastLoginIp(ipAddr);
        usersMapper.updateByPrimaryKeySelective(users);
    }



    public Return Add(JSONObject json) {
        Return re = new Return();
        Long user_id = json.getLong("user_id");
        String username = json.getString("username");
        String name = json.getString("name");
        Integer sex = json.getInteger("sex");
        Long department_id = json.getLong("department_id");
        String email = json.getString("email");
        String phone = json.getString("phone");
        String birth_date = json.getString("birth_date");
        String position = json.getString("position");
        String hire_date = json.getString("hire_date");
        Integer status = json.getInteger("status");
        JSONArray user_roles = json.getJSONArray("user_roles");
        Users users=new Users();
        users.setName(name);
        users.setEmail(email);
        users.setSex(sex);
        users.setDepartmentId(department_id);
        users.setPhone(phone);
        users.setBirthDate(birth_date);
        users.setPosition(position);
        users.setHireDate(hire_date);
        users.setStatus(status);
        if (user_id>0){
            users.setUserId(user_id);
            usersMapper.updateByPrimaryKeySelective(users);
            roles(users.getUserId(),user_roles);
            re.setCode(200);
            re.setMsg("成功");
        }else {
            UsersExample usersExample=new UsersExample();
            usersExample.createCriteria().andUsernameEqualTo(username);
            List<Users> users1 = usersMapper.selectByExample(usersExample);
            if (users1.size()>0){
                re.setCode(201);
                re.setMsg("账号已存在，不可重复添加！");
            }else {
                users.setUsername(username);
                users.setPassword("123456");
                users.setCreatedAt(new Date());
                usersMapper.insertSelective(users);
                roles(users.getUserId(),user_roles);
                re.setCode(200);
                re.setMsg("成功");

            }

        }
        return re;
    }

    public void roles(Long user_id,JSONArray user_roles ) {
        baseDaoMapper.deleteSql("DELETE from user_roles where user_id="+user_id+" ");
        for (int i=0; i<user_roles.size();i++){
            Integer integer = user_roles.getInteger(i);
            UserRoles userRoles=new UserRoles();
            userRoles.setRoleId(integer);
            userRoles.setUserId(user_id);
            userRoles.setAssignedAt(new Date());
            userRolesMapper.insertSelective(userRoles);
        }
    }



    public Integer Count(JSONObject json) {
        String name = json.getString("name");
        String tj="";
        if (name!=null){
            if (name!=""){ tj=tj+"  and  name like '%"+name+"%'  "; }
        }
        String SQL="SELECT  count(user_id) as mun  from users where employee_id=0 "+tj+"   ";
        Integer integer = baseDaoMapper.selectCountSql(SQL);
        return integer;
    }
    public JSONArray List (JSONObject json) {
        Integer page = json.getInteger("page");
        Integer limit = json.getInteger("limit");
        String name = json.getString("name");
        String tj="";
        if (name!=null){
            if (name!=""){ tj=tj+"  and  a.name like '%"+name+"%'  "; }
        }
        String SQL="SELECT a.*,b.department_name FROM users a " +
                " LEFT JOIN departments b on a.department_id=b.department_id " +
                " where a.employee_id=0  "+tj+"  " +
                " ORDER BY a.user_id desc LIMIT "+(page-1)*limit+","+limit+"  ";
        List<LinkedHashMap<String, Object>> linkedHashMaps = baseDaoMapper.selectSql(SQL);
        JSONArray listArray = JSON.parseArray(JSON.toJSONString(linkedHashMaps));
        JSONArray array=new JSONArray();

        for (int i=0; i<listArray.size();i++){
            JSONObject jsonObject = listArray.getJSONObject(i);
            JSONObject js=new JSONObject();
            js.put("user_id",jsonObject.getLong("user_id"));
            js.put("sex",jsonObject.getInteger("sex"));
            js.put("name",jsonObject.getString("name"));
            js.put("username",jsonObject.getString("username"));
            js.put("email",jsonObject.getString("email"));
            js.put("avatar_url",jsonObject.getString("avatar_url"));
            js.put("phone",jsonObject.getString("phone"));
            js.put("birth_date",jsonObject.getString("birth_date"));
            js.put("department_id",jsonObject.getLong("department_id"));
            js.put("position",jsonObject.getString("position"));
            js.put("hire_date",jsonObject.getString("hire_date"));
            js.put("status",jsonObject.getInteger("status"));
            js.put("last_login_time",jsonObject.getString("last_login_time"));
            js.put("last_login_ip",jsonObject.getString("last_login_ip"));
            js.put("created_at",jsonObject.getString("created_at"));
            js.put("department_name",jsonObject.getString("department_name"));


            String SQL1="SELECT b.role_id,b.role_name FROM user_roles a LEFT JOIN roles b on a.role_id=b.role_id where a.user_id="+jsonObject.getLong("user_id")+"  ";
            List<LinkedHashMap<String, Object>> linkedHashMaps1 = baseDaoMapper.selectSql(SQL1);
            JSONArray userRoles = JSON.parseArray(JSON.toJSONString(linkedHashMaps1));

            js.put("roleList",userRoles);
            JSONArray jsonArray=new JSONArray();
            for (int k=0; k<userRoles.size();k++){
                Integer RoleId = userRoles.getJSONObject(k).getInteger("role_id");
                jsonArray.add(RoleId);
            }
            js.put("checkedKeys",jsonArray);
            array.add(js);
        }
        return array;
    }
    public Return del(JSONObject json) {
        Return re = new Return();
        Long id = json.getLong("user_id");
        usersMapper.deleteByPrimaryKey(id);
        baseDaoMapper.deleteSql("DELETE from user_roles where user_id="+id+" ");
        re.setCode(200);
        re.setMsg("成功");
        return re;
    }
}
